﻿using System;
using System.Net;
using System.Net.Http;

namespace Neo4jConnect.Rest
{
    public class HttpClientIndexService : IIndexService
    {
        private readonly HttpClient client;

        public HttpClientIndexService(HttpClient client)
        {
            this.client = client;
        }

        public string GetIndexes()
        {
            return client
                .Get("index/node")
                .EnsureStatusCode(HttpStatusCode.OK)
                .Content.ReadAsString();
        }
        
        public string AddIndex(string indexData)
        {                        
            return client
                .Post("index/node", new StringContent(indexData, null, "application/json"))
                .EnsureStatusCode(HttpStatusCode.Created)
                .Content.ReadAsString();            
        }
        
        public string GetRelationshipIndexes()
        {
            return client
                .Get("index/relationship")
                .EnsureStatusCode(HttpStatusCode.OK)
                .Content.ReadAsString();                        
        }

        public string AddIndexToNode(string indexName, ulong nodeId, string key, string value)
        {
            var requestUri = string.Format("index/node/{0}/{1}/{2}", indexName, key, Uri.EscapeDataString(value));

            Uri nodeUri = null;
            Uri.TryCreate(client.BaseAddress, string.Format("node/{0}", nodeId), out nodeUri);

            return client
                .Post(requestUri, new StringContent(@"""" + nodeUri.ToString() + @"""", null, "application/json"))
                .EnsureStatusCode(HttpStatusCode.Created)
                .Content.ReadAsString();            
        }

        public void AddIndexToRelationship()
        {
        }

        public void RemoveIndex()
        {
        }
        
        public string QueryIndex(string indexName, string key, string value)
        {            
            return client
                .Get(string.Format("index/node/{0}/{1}/{2}", indexName, key, value))
                .EnsureStatusCode(HttpStatusCode.OK)
                .Content.ReadAsString();                       
        }
    }
}
